/**
 * 
 */
package com.aaron.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.rpc.AsyncCallback;

import org.mcarthur.sandy.gwt.login.client.*;

/**
 * @author aaron
 * 
 */
public class VivCode implements EntryPoint {
	private static User user;
	private DockPanel dock_panel;
	/* (non-Javadoc)
	 * @see com.google.gwt.core.client.EntryPoint#onModuleLoad()
	 */
	public void onModuleLoad() {
		//determine if the user is logged in
		if(!isLoggedIn()){
			this.login();
		}
		else if(isEditing()){
			dock_panel=new DockPanel();
			RootPanel.get().add(dock_panel);
			dock_panel.add(createLinksPanel(), DockPanel.NORTH);
			dock_panel.add(new Logo(), DockPanel.NORTH);
			dock_panel.add(createEditor(), DockPanel.CENTER);
		}
		else{
			dock_panel=new DockPanel();
			RootPanel.get().add(dock_panel);
			dock_panel.add(createLinksPanel(), DockPanel.NORTH);
			dock_panel.add(new Logo(), DockPanel.NORTH);
			//dock_panel.add(new Label(getAuth()), DockPanel.SOUTH);
			dock_panel.add(createWorkspace(), DockPanel.CENTER);
		}
		// logged in check history
		// if history is for workspace
		// display workspace
		// else if history is for editor
		// display editor
		// else
		// display workspace
		
		//test:
		
	}
	/**
	 * Fetches the current login status
	 * @return {true:logged in, false:not logged in}
	 */
	private static native boolean isLoggedIn()/*-{
	  return $wnd.location.search.indexOf("auth=")!=-1;
	}-*/;
	public static native boolean isEditing()/*-{
	  return $wnd.location.search.indexOf("edit=")!=-1;
	}-*/;
	public static native String getGetVar(String name)/*-{
	  var getVars = new Array();
		var qString = unescape(top.location.search.substring(1));
		var pairs = qString.split(/\&/);
		for (var i in pairs) {
			var nameVal = pairs[i].split(/\=/);
			getVars[nameVal[0]] = nameVal[1];
			}	
		return getVars[name];
	}-*/;
	public static String getAuth(){
		return getGetVar("auth");
	}
	public static String getEdit(){
		return getGetVar("edit");
	}
	public static native String getCurrentPath()/*-{
	  return  $wnd.location.protocol+"//"+$wnd.location.host+"/"+$wnd.location.pathname;
	}-*/;
	/**
	 * Redirect to login page
	 */
	public static native void redirectToHome()/*-{
	  $wnd.location.search="";
	}-*/;

	public static native void closeWindow()/*-{
	  $wnd.close();
	}-*/;
	/**
	 * Shows a login panel which accepts username and password.
	 * When the Login button is clicked a RPC is made via the UserService.
	 * <p>
	 * If the user is properly authenticated the login panel is disposed of,
	 * VivCode.setLoggedStatus(true) is called, and VivCode.user is
	 * populated with an instance of {@link User} corresponding to
	 * the user that logged in.
	 * <p>
	 * If the user is not properly authenticated, the login panel is
	 * disposed of and a new panel is created in its place.
	 */
	private void login(){
		LoginPanel login_panel=new LoginPanel(
				new LoginPanel.LoginListener(){
					public void onSubmit(LoginPanel login_panel){
						UserServiceAsync userService =UserService.Util.getInstance();
						
						class LoginAsyncCallback implements AsyncCallback{
							private LoginPanel login_panel;
							public LoginAsyncCallback(LoginPanel login_panel){
								this.login_panel=login_panel;
							}
							public void onSuccess(Object result) {
								VivCode.user=(User)result;
								RootPanel.get().remove(this.login_panel);
								//redirect to logged in url
								setAuthAndRedirect(VivCode.user.getAuth());
							}

							public void onFailure(Throwable caught) {
								Exception e=(Exception)caught;
								RootPanel.get().remove(this.login_panel);
								RootPanel.get().add(new Label("Login failed: "+e.getLocalizedMessage()));
								login();
							}
						}

						AsyncCallback callback = new LoginAsyncCallback(login_panel);
						userService.login(login_panel.getUsername(), login_panel.getPassword(), callback);
					}
				}
		);
		login_panel.setStyleName("vivcode-login-panel");
		RootPanel.get().add(login_panel);

	}
	/**
	 * Redirect to logged in url
	 */
	private static native void setAuthAndRedirect(String auth)/*-{
	  $wnd.location.search="?auth="+auth;
	}-*/;
	/**
	 * Shows a {@link WorkspacePanel} widget on the screen
	 *
	 */
	private static Widget createWorkspace(){
		return new WorkspacePanel(getAuth());
	}
	private static Widget createLinksPanel(){
		return new LinksPanel(getAuth());
	}
	private static Widget createEditor(){
		return new ProjectPanel(getEdit(), getAuth());
	}
}
